package com.project.srtp.secure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.srtp.secure.dao.entity.EncryptionSenderKeyDO;
import com.project.srtp.secure.dao.mapper.EncryptionSenderKeyMapper;
import com.project.srtp.secure.dto.req.EncryptionSenderKeyReqDTO;
import com.project.srtp.secure.service.EncryptionSenderKeyService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

/**
 * @author 曹行阳
 * @version 0.1
 * @date 2025/6/16 20:25
 */
@Service
public class EncryptionSenderKeyServiceImpl extends ServiceImpl<EncryptionSenderKeyMapper, EncryptionSenderKeyDO> implements EncryptionSenderKeyService {
    @Override
    public void storeEncryptionSenderKey(EncryptionSenderKeyReqDTO request) {
        // 构造查询条件
        LambdaQueryWrapper<EncryptionSenderKeyDO> queryWrapper = Wrappers.lambdaQuery(EncryptionSenderKeyDO.class)
                .eq(EncryptionSenderKeyDO::getKeyId, request.getKeyId())
                .eq(EncryptionSenderKeyDO::getUserId, request.getUserId())
                .eq(EncryptionSenderKeyDO::getPartyId, request.getPartyId());

        EncryptionSenderKeyDO encryptionSenderKeyDO = EncryptionSenderKeyDO.builder()
                .keyId(request.getKeyId())
                .preKeyId(request.getPreKeyId())
                .senderKey(request.getSenderKey())
                .identityKeyId(request.getIdentityKeyId())
                .chainId(request.getChainId())
                .step(request.getStep())
                .userId(request.getUserId())
                .partyId(request.getPartyId())
                .build();

        EncryptionSenderKeyDO existing = baseMapper.selectOne(queryWrapper);
        if (existing != null) {
            encryptionSenderKeyDO.setId(existing.getId());
            boolean success = this.updateById(encryptionSenderKeyDO);
            if (!success) {
                throw new RuntimeException("更新失败");
            }
        } else {
            try {
                boolean success = this.save(encryptionSenderKeyDO);
                if (!success) {
                    throw new RuntimeException("插入失败");
                }
            } catch (DuplicateKeyException ex) {
                log.warn("插入时主键冲突，可能并发写入已存在: ");
                EncryptionSenderKeyDO check = baseMapper.selectOne(queryWrapper);
                if (check == null) {
                    throw new RuntimeException("插入冲突后未能找到记录，数据可能异常");
                }
            }
        }
    }



    @Override
    public String getSessionIdByPartyId(String partyId) {
        LambdaQueryWrapper<EncryptionSenderKeyDO> queryWrapper = Wrappers.lambdaQuery(EncryptionSenderKeyDO.class)
                .eq(EncryptionSenderKeyDO::getPartyId, partyId)
                .orderByDesc(EncryptionSenderKeyDO::getId)
                .last("LIMIT 1");
        EncryptionSenderKeyDO encryptionSenderKeyDO = baseMapper.selectOne(queryWrapper);
        return encryptionSenderKeyDO.getPartyId();
    }

}
